<template>
  <div class="afterManage-subInvest-page app-container">
    <div class="container">
      <div class="container-header">
        <div class="left">
          <div class="title">子投资列表</div>
          <el-form
            ref="dataForm"
            :inline="true"
            label-width="80px"
            :model="dataForm"
          >
            <el-form-item label="" prop="investName">
              <el-input
                v-model="dataForm.investName"
                size="small"
                @keyup.enter.native="getList"
                clearable
                placeholder="请输入子投资名称"
                style="width: 200px"
              ></el-input>
            </el-form-item>
            <el-form-item label="" prop="investStrategyName">
              <el-input
                v-model="dataForm.investStrategyName"
                size="small"
                @keyup.enter.native="getList"
                clearable
                placeholder="请输入关联策略名称"
                style="width: 200px"
              ></el-input>
            </el-form-item>
            <el-form-item label="" prop="investStatus">
              <el-select
                v-model="dataForm.investStatus"
                size="small"
                @change="getList"
                clearable
                placeholder="投资状态"
                style="width: 200px"
              >
                <el-option
                  v-for="item in statusList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="" prop="mark">
              <el-input
                v-model="dataForm.mark"
                size="small"
                @keyup.enter.native="getList"
                clearable
                placeholder="请输入子投资备注"
                style="width: 200px"
              ></el-input>
            </el-form-item>
            <el-form-item style="margin-left: 20px">
              <el-button size="small" class="bg-green" @click="getList"
                >查询</el-button
              >
              <el-button size="small" @click="resetForm">重置</el-button>
              <span
                style="margin-left: 10px; cursor: pointer; color: #1890ff"
                @click="isSelectMore = !isSelectMore"
              >
                {{ isSelectMore ? "收起筛选" : "展示筛选" }}
                <i
                  :class="
                    isSelectMore ? 'el-icon-arrow-down' : 'el-icon-arrow-right'
                  "
                />
              </span>
            </el-form-item>
          </el-form>
        </div>
        <div class="right-btn">
          <el-button
            v-if="!isOpen"
            size="small"
            type="primary"
            @click="addOrUpdateHandle()"
          >
            <i class="el-icon-plus el-icon--right"></i>
            添加
          </el-button>
        </div>
      </div>

      <el-form
        v-show="isSelectMore"
        ref="dataForm2"
        :inline="true"
        label-position="left"
        label-width="68px"
        :model="dataForm"
        class="form2"
      >
        <el-form-item label="投资收益">
          <el-input
            v-model="dataForm.startIncomeRate"
            @keyup.enter.native="getList"
            style="width: 80px"
            size="mini"
          >
            <span slot="suffix">%</span>
          </el-input>
          <span class="grayLine">-</span>
          <el-input
            v-model="dataForm.endIncomeRate"
            @keyup.enter.native="getList"
            style="width: 80px"
            size="mini"
          >
            <span slot="suffix">%</span>
          </el-input>
        </el-form-item>
        <el-form-item label="投资时间" style="margin-left: 15px">
          <el-date-picker
            size="small"
            v-model="dataForm.investStarttime"
            type="date"
            value-format="yyyy-MM-dd"
            style="width: 135px"
            placeholder="开始日期"
          ></el-date-picker>
          <span class="grayLine">-</span>
          <el-date-picker
            size="small"
            v-model="dataForm.investEndtime"
            type="date"
            value-format="yyyy-MM-dd"
            @keyup.enter.native="getList"
            style="width: 135px"
            placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item
          prop="investIndex"
          label="对标指数"
          style="margin-left: 15px"
        >
          <indexSelectTree
            :multiple="false"
            :width="200"
            size="small"
            :indexType.sync="dataForm.investIndex"
          ></indexSelectTree>
        </el-form-item>
      </el-form>

      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="list"
        stripe
        fit
        size="mini"
        @row-click="submitHandle"
        @sort-change="sortChange"
        :header-cell-style="{ color: '#333' }"
        style="width: 100%"
      >
        <el-table-column
          prop="investId"
          label="编号"
          align="left"
          width="78"
          fixed
          sortable="custom"
        ></el-table-column>
        <el-table-column prop="" label="" align="center" width="40" fixed>
          <template slot-scope="scope">
            <el-tooltip
              effect="dark"
              :content="scope.row.netWorthStatusText"
              placement="right"
            >
              <svg-icon
                v-show="scope.row.netWorthStatusText"
                class="strategyName_tips"
                icon-class="tips"
              />
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          prop="investName"
          label="子投资名称"
          align="left"
          min-width="290"
          fixed
          sortable="custom"
        >
          <template slot-scope="{ row }">
            <div
              style="
                display: flex;
                align-items: center;
                justify-content: flex-start;
              "
            >
              <div
                style="
                  overflow: hidden;
                  text-overflow: ellipsis;
                  display: -webkit-box;
                  -webkit-line-clamp: 2;
                  -webkit-box-orient: vertical;
                "
                :title="row.investName"
              >
                <span
                  v-if="row.hasNetworth"
                  style="cursor: pointer; color: #1890ff"
                  @click.stop="groupDeltailHandle(row.investId)"
                  >{{ row.investName }}</span
                >
                <span
                  v-else
                  style="cursor: pointer; color: #666"
                  @click.stop="$message('该子投资净值不存在，无法查看详情')"
                >
                  {{ row.investName }}
                </span>
              </div>
              <el-popover
                v-if="row.mark"
                popper-class="policyManage_popover"
                trigger="hover"
                placement="right"
                style="cursor: pointer"
              >
                <div class="flex-vh-center">
                  {{ row.mark }}
                </div>
                <div slot="reference" style="display: inline-block">
                  <i
                    class="el-icon-document fontdoc"
                    style="font-size: 16px"
                  ></i>
                </div>
              </el-popover>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="investParentName"
          label="所属投资"
          min-width="100"
          sortable="custom"
          fixed
          show-overflow-tooltip
        ></el-table-column>
        <!-- <el-table-column prop="mark" label="备注" sortable="custom" width="102" fixed show-overflow-tooltip align="left"></el-table-column> -->
        <el-table-column prop="" label="对比" align="center" fixed>
          <template slot-scope="{ row, $index }">
            <span
              v-if="row.hasNetworth"
              class="pointer"
              :class="{ fontcolor: !row.addContrast }"
              @click="addContrasthandle(row, $index)"
            >
              <span v-show="!row.addContrast" class="iconfont icon-jia" />
              <span
                v-show="row.addContrast"
                class="iconfont icon-check contrastGray"
              />
              <span
                :class="{ contrastGray: row.addContrast }"
                style="padding-left: 2px"
                >{{ !row.addContrast ? "对比" : "已加" }}</span
              >
            </span>
            <span
              v-else
              class="contrastGray"
              @click.stop="$message('该投资净值不存在，不能对比')"
            >
              <span class="iconfont icon-jia" />
              <span style="padding-left: 2px">对比</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="networthTime"
          label="净值日期"
          sortable="custom"
          width="100"
          align="center"
        >
          <template slot-scope="{ row }">
            <span>{{ row.networthTime | parseTime }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="unitNetworth"
          label="单位净值"
          sortable="custom"
          min-width="130"
          show-overflow-tooltip
          align="center"
        ></el-table-column>
        <el-table-column
          prop="unitNetworth"
          label="累计净值"
          sortable="custom"
          min-width="130"
          show-overflow-tooltip
          align="center"
        ></el-table-column>
        <el-table-column
          prop="currentEquity"
          label="资产金额(万元)"
          sortable="custom"
          width="140"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="currentShare"
          label="资产份额(份)"
          sortable="custom"
          min-width="130"
          show-overflow-tooltip
          align="center"
        ></el-table-column>
        <el-table-column
          prop="incomeRate"
          label="收益率"
          sortable="custom"
          min-width="120"
          show-overflow-tooltip
          align="center"
        >
          <template slot-scope="{ row }">
            <span
              v-if="row.incomeRate || row.incomeRate !== null"
              :class="row.incomeRate >= 0 ? 'positiveFc' : 'negativeFc'"
              >{{ row.incomeRate }}%</span
            >
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="incomeRateToday"
          label="当日收益率"
          sortable="custom"
          min-width="120"
          show-overflow-tooltip
          align="center"
        >
          <template slot-scope="{ row }">
            <span
              v-if="row.incomeRateToday || row.incomeRateToday !== null"
              :class="row.incomeRateToday >= 0 ? 'positiveFc' : 'negativeFc'"
              >{{ row.incomeRateToday }}%</span
            >
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="incomeRateWeek"
          label="近1周收益率"
          sortable="custom"
          min-width="125"
          show-overflow-tooltip
          align="center"
        >
          <template slot-scope="{ row }">
            <span
              v-if="row.incomeRateWeek || row.incomeRateWeek !== null"
              :class="row.incomeRateWeek >= 0 ? 'positiveFc' : 'negativeFc'"
              >{{ row.incomeRateWeek }}%</span
            >
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="incomeRateMonth"
          label="近1月收益率"
          sortable="custom"
          min-width="125"
          show-overflow-tooltip
          align="center"
        >
          <template slot-scope="{ row }">
            <span
              v-if="row.incomeRateMonth"
              :class="row.incomeRateMonth >= 0 ? 'positiveFc' : 'negativeFc'"
              >{{ row.incomeRateMonth }}%</span
            >
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="incomeRateHalfYear"
          label="近6月收益率"
          sortable="custom"
          min-width="125"
          show-overflow-tooltip
          align="center"
        >
          <template slot-scope="{ row }">
            <span
              v-if="row.incomeRateHalfYear"
              :class="row.incomeRateHalfYear >= 0 ? 'positiveFc' : 'negativeFc'"
              >{{ row.incomeRateHalfYear }}%</span
            >
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="incomeRateYear"
          label="近1年收益率"
          sortable="custom"
          min-width="125"
          show-overflow-tooltip
          align="center"
        >
          <template slot-scope="{ row }">
            <span
              v-if="row.incomeRateYear"
              :class="row.incomeRateYear >= 0 ? 'positiveFc' : 'negativeFc'"
              >{{ row.incomeRateYear }}%</span
            >
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="investStrategyName"
          label="关联策略"
          sortable="custom"
          min-width="140"
          show-overflow-tooltip
          align="center"
        ></el-table-column>
        <el-table-column
          prop="investIndexText"
          label="对标指数"
          sortable="custom"
          min-width="120"
          show-overflow-tooltip
          align="center"
        ></el-table-column>
        <el-table-column
          prop="investStarttime"
          label="投资时间"
          sortable="custom"
          min-width="100"
          show-overflow-tooltip
          align="center"
        ></el-table-column>
        <el-table-column
          prop="investStatusName"
          label="投资状态"
          sortable="custom"
          min-width="100"
          show-overflow-tooltip
          align="center"
        ></el-table-column>
        <el-table-column
          prop="username"
          label="创建人"
          sortable="custom"
          min-width="100"
          show-overflow-tooltip
          align="center"
        ></el-table-column>
        <el-table-column
          v-if="!isOpen"
          label="操作"
          align="center"
          width="220"
          fixed="right"
        >
          <template slot-scope="{ row }">
            <el-button
              class="filter-item"
              size="mini"
              :disabled="row.addType == 1"
              icon="el-icon-edit-outline"
              @click="enternetValueHandle(row)"
            >
              录入净值
            </el-button>
            <!-- <el-button class="filter-item" size="mini" style="margin-left: 10px;"  icon="el-icon-edit" @click="addOrUpdateHandle(row.investId)">
              调仓
            </el-button> -->
            <el-popover
              popper-class="policyManage_popover"
              trigger="hover"
              placement="bottom"
            >
              <div class="flex-vh-center">
                <el-button
                  class="filter-item"
                  size="mini"
                  @click="subscribeHandle(row.investId, row.investName, 1)"
                >
                  申购/入金
                </el-button>
                <el-button
                  style="margin: 10px 0"
                  class="filter-item"
                  size="mini"
                  @click="subscribeHandle(row.investId, row.investName, 2)"
                >
                  赎回/出金
                </el-button>
                <el-button
                  style="margin: 0"
                  :class="{ 'filter-item': true, focus: row.confirmFlag === 1 }"
                  size="mini"
                  @click="openSetWarehouse(row)"
                >
                  调仓记录
                </el-button>
              </div>
              <span class="operationMore" slot="reference">
                <el-button
                  :class="{ 'filter-item': true, focus: row.confirmFlag === 1 }"
                  size="mini"
                >
                  调仓
                </el-button>
              </span>
            </el-popover>
            <el-popover
              popper-class="policyManage_popover"
              trigger="hover"
              placement="bottom"
            >
              <div class="flex-vh-center">
                <el-button
                  class="filter-item"
                  size="mini"
                  @click="deleteEnternetValueHandle(row.investId)"
                >
                  清空净值
                </el-button>
                <el-button
                  class="filter-item"
                  size="mini"
                  style="margin: 10px 0 0 0"
                  icon="el-icon-edit"
                  @click="addOrUpdateHandle(row.investId)"
                >
                  编辑
                </el-button>
                <el-button
                  class="filter-item"
                  size="mini"
                  style="margin: 10px 0 0 0"
                  icon="el-icon-delete"
                  @click="deleteHandle(row)"
                >
                  删除
                </el-button>
              </div>
              <span class="operationMore" slot="reference">...</span>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.pageCurrent"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />

      <addOrUpdateOpen
        v-if="addOrUpdateView"
        ref="addOrUpdateOpen"
        :userId="userId"
        @closeOpen="getList"
      >
      </addOrUpdateOpen>
      <enternetValueOpen
        ref="enternetValueOpen"
        v-if="hasEnternetValueOpen"
        @closeOpen="getList"
      ></enternetValueOpen>
      <globalContrastOpen
        ref="globalContrastOpen"
        :list="contrastList"
      ></globalContrastOpen>
      <subscribeOpen
        v-if="subscribeView"
        ref="subscribeOpen"
        :userId="userId"
        @closeOpen="getList"
      ></subscribeOpen>
      <setWarehouse
        :row="listRow"
        :type="2"
        :warehouseDialogVisible.sync="warehouseDialogVisible"
        @closeOpen="getList"
      ></setWarehouse>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import Pagination from "@/components/Pagination";
import indexSelectTree from "@/components/investComn/indexSelectTree.vue";
import { queryInvestInfoByPage, delInvest } from "@/api/subInvest";
import addOrUpdateOpen from "./addOrUpdateOpen.vue";
import { rmoney } from "@/utils";
import { STATUS_OPTIONS } from "../const";
import enternetValueOpen from "@/views/afterManage/component/enternetValueOpen.vue";
import globalContrastOpen from "@/components/investComn/globalContrastOpen.vue";
import subscribeOpen from "@/views/afterManage/component/subscribeOpen.vue";
import setWarehouse from "@/views/afterManage/component/setWarehouse.vue";
import { deleteNetWorthByStrategyId } from "@/api/policyManage";

export default {
  name: "AfterManageCombination",
  components: {
    addOrUpdateOpen,
    Pagination,
    indexSelectTree,
    enternetValueOpen,
    globalContrastOpen,
    subscribeOpen,
    setWarehouse,
  },
  props: {
    isOpen: {
      type: Boolean,
      defaultL: false,
    },
  },
  data() {
    return {
      isSelectMore: false,
      addOrUpdateView: false,
      subscribeView: false,
      listLoading: false,
      dataForm: {
        mark: "",
        investName: "",
        investStatus: "",
        investStrategyName: "",
      },
      total: 0,
      list: [],
      listQuery: {
        pageCurrent: 1,
        limit: 20,
      },
      rmoney: Function,
      listRow: {},
      warehouseDialogVisible: false,
      orderBy: {},
      statusList: STATUS_OPTIONS,
      hasEnternetValueOpen: false,
    };
  },
  computed: {
    ...mapGetters(["userId", "contrastList"]),
  },
  watch: {
    contrastList(newList, oldList) {
      if (newList.length == oldList.length) {
        // todo 此处newList==oldList则是数组减少，未知原因
        this.syncContrastListHandle();
      }
      if (!newList.length) {
        this.list.forEach((row, i) => {
          row.addContrast = false;
          this.$set(this.list, i, row);
        });
      }
    },
  },
  created() {
    this.rmoney = rmoney;
    if (this.$route.query.classifyId) {
      this.dataForm.classifyId = this.$route.query.classifyId;
    }
    if (this.$route.query.compositionId) {
      this.dataForm.compositionId = this.$route.query.compositionId;
      // this.dataForm.investParentId = this.$route.query.investId
      // this.dataForm.investName = this.$route.query.investName
    }
    this.getList();
  },
  methods: {
    subscribeHandle(investId, investName, isSubscribe) {
      this.subscribeView = true;
      this.$nextTick(() => {
        this.$refs.subscribeOpen.init(investId, investName, isSubscribe, 2);
      });
    },
    openSetWarehouse(row) {
      this.listRow = row;
      this.warehouseDialogVisible = true;
    },
    sortChange(column) {
      if (!column.order) {
        this.orderBy = {};
      } else {
        this.orderBy = {
          [column.prop]: column.order == "ascending" ? "asc" : "desc",
        };
      }
      this.getList();
    },
    // 同步对比框数据和列表数据
    syncContrastListHandle() {
      if (!this.contrastList.length) {
        this.list.forEach((row, i) => {
          row.addContrast = false;
          this.$set(this.list, i, row);
        });
      } else {
        const list = this.contrastList.filter(
          (item) => item.contrastObj.type == 5
        );
        this.list.forEach((row, index) => {
          row.addContrast = false;
          this.$set(this.list, index, row);
          const i = list.findIndex(
            (item) => item.contrastObj.id == row.investId
          );
          if (i != -1) {
            this.list[index].addContrast = true;
          }
        });
      }
    },
    addContrasthandle(row, i) {
      this.$refs.globalContrastOpen.showOpen = true;
      this.$store.commit("contrast/toggleShowOpen", true);
      row.addContrast = !row.addContrast;
      if (this.contrastList.length == 20) {
        this.$message({
          message: "最多添加20条数据",
          type: "warning",
        });
        return;
      }
      this.$set(this.list, i, row); // 更新表格数据
      if (row.addContrast) {
        row.contrastObj = {
          type: 5,
          id: row.investId,
          name: row.investName,
          enterTime: row.investStarttime,
          annualFluctuations: row.netWorthDetialBean.yearAnnualfluctuationsRate,
          annualizedIncome: row.netWorthDetialBean.yearAnnualizedincomeRate
        };
        this.$store.commit("contrast/addContrastList", row);
      } else {
        const i = this.contrastList.findIndex(
          (item) =>
            item.contrastObj.id == row.investId && item.contrastObj.type == 5
        );
        this.$store.commit("contrast/removeContrastList", i);
      }
    },
    enternetValueHandle(row) {
      this.hasEnternetValueOpen = true;
      this.$nextTick(() => {
        this.$refs.enternetValueOpen.init({
          investName: null,
          strategyId: row.investId,
          strategyName: row.investName,
          userId: this.userId,
          networth: row.unitNetworth,
          networthTime: row.networthTime,
          strategyNetWorthStyle: 0,
        });
      });
    },
    groupDeltailHandle(id) {
      this.$router.push({
        path: `/afterManage/subInvest/details/${id}`,
        query: {
          userId: this.userId,
        },
      });
    },
    submitHandle(row) {
      this.$emit("selctCombination", {
        groupId: row.groupId,
        groupName: row.groupName,
      });
    },
    addOrUpdateHandle(investId) {
      this.addOrUpdateView = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdateOpen.init(investId);
      });
    },
    deleteHandle(row) {
      this.$confirm(`确认删除分组名称【${row.investName}】此条数据？`, "提示", {
        type: "warning",
      })
        .then((_) => {
          if (row.hasParent) {
            this.$message({
              type: "error",
              message: "该子投资已被投资关联,无法删除",
            });
            return;
          }
          delInvest({
            investId: row.investId,
            userId: this.userId,
          }).then((res) => {
            if (res.code == 0) {
              this.$notify({
                message: res.msg,
                type: "success",
                duration: 2000,
              });
              this.getList();
            }
          });
        })
        .catch((_) => {});
    },
    resetForm() {
      this.$refs.dataForm.resetFields();
      this.dataForm = {
        investStrategyName: "",
        startIncomeRate: null,
        endIncomeRate: null,
        investStarttime: null,
        investEndtime: null,
        investIndex: null,
      };
      // 不重置跳转条件
      if (this.$route.query.classifyId) {
        this.dataForm.classifyId = this.$route.query.classifyId;
      }
      this.getList();
    },
    getList() {
      this.listLoading = true;
      queryInvestInfoByPage({
        ...this.dataForm,
        ...this.listQuery,
        orderBy: this.orderBy,
        userId: this.userId,
        investManageType: 2,
      }).then((res) => {
        this.listLoading = false;
        this.list = res.body.list;
        this.total = res.body.total;

        if (this.contrastList.length) this.syncContrastListHandle();
      });
    },
    deleteEnternetValueHandle(strategyId) {
      this.$confirm("确认清空该策略净值？", "提示", {
        type: "warning",
      })
        .then((_) => {
          deleteNetWorthByStrategyId({ strategyId: strategyId }).then((res) => {
            if (res.code == 0) {
              this.$notify({
                type: "success",
                message: "清空净值成功",
                duration: 2000,
              });
              this.getList();
            }
          });
        })
        .catch((_) => {});
    },
  },
};
</script>

<style lang="scss" scoped>
.focus {
  color: #409eff;
  border-color: #c6e2ff;
  background-color: #ecf5ff;
}
.afterManage-subInvest-page {
  .operationMore {
    padding-left: 10px;
    font-weight: bold;
    cursor: pointer;
  }

  .grayLine {
    color: #bfbfbf;
  }

  .icon-jia {
    font-size: 12px;
  }
  .strategyName_tips {
    min-width: 18px;
    font-size: 18px;
    color: #fb9391;
    margin-left: 2px;
  }
}
</style>
